﻿using fuzhu;
using SqlSugar;
using System.Collections.Generic;
using System.Data;
using U8COWeb;
using XXX.Bo;
using XXX.Common;
using XXX.Models;
using XXX.Models.AS;
using ZDEntity;

namespace Yonyou.U8.BO
{
    /// <summary>
    ///不能直接继承，因为调用co时，根据AS_Department类直接转换
    /// </summary>
    public class WarehouseVM
    {
        //当前的数据库连接字符串
        public string conStr { get; set; }
        public string xmlConfig { get; set; }
        public static string cDatabase = "";

        public AS_Warehouse entity { get; set; }

        public WarehouseVM()
        {
            //conStr
            conStr = CanShu.conStr;
            //初始化定义xmlconfig
            xmlConfig = XmlOperation.GetConfigXML();
        }

        /// <summary>
        /// 获得操作员有权限的仓库，备注里填写PDA 
        /// </summary>
        /// <param name="cuserid">操作员</param>
        /// <returns></returns>
        public RetModel2 AA_GetWarehouseByUser( string cuserid)
        {
            try
            {
                using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = conStr,
                    DbType = SqlSugar.DbType.SqlServer,
                    IsAutoCloseConnection = true
                }))
                { 
                    string sqlwh = string.Format(@"SELECT cWhCode,cWhName, bWhpos  as bWhPos FROM dbo.Warehouse where cwhmemo like '%PDA%' ");
                    //是不是权限主管或者账套主管
                    string sql = "SELECT bAuthControl FROM AA_BusObject_base WHERE cBusObId='warehouse' AND langid='zh-CN' ";

                    int iWhControl = DbHelper.GetDbInt(db.Ado.GetScalar(sql));
                    if (iWhControl == 1)
                    {
                        //人员是否是账套主管

                        sql = string.Format(@"SELECT COUNT(*) sl FROM UFSystem..ua_role  WHERE cgroup_id = 'DATA-MANAGER' 
AND cUser_Id = '{0}'", cuserid);
                        int icnt = DbHelper.GetDbInt(db.Ado.GetScalar(sql));
                        //只是当前账套的账套主管
                        if (icnt == 0)
                        {
                            sql = $@"select COUNT(*) sl from UFSystem..UA_HoldAuth where cUser_Id = '{cuserid}' and cAcc_Id = '{CanShu.cZT}' and cAuth_Id = 'Admin'";
                            icnt = DbHelper.GetDbInt(db.Ado.GetScalar(sql));
                        }


                        if (icnt == 0)
                        {
                            //有仓库主管权限
                            sql = string.Format(@"SELECT COUNT(*) sl FROM AA_holdbusobject a
LEFT JOIN UFSystem..UA_Role b ON  a.cUserId = b.cGroup_Id
WHERE iAdmin = 1 AND CBusObId = 'warehouse'
AND((isUserGroup = 0 AND cUserId = '{0}')    OR(isUserGroup = 1 AND b.cUser_Id = '{0}'))", cuserid);
                            icnt = DbHelper.GetDbInt(db.Ado.GetScalar(sql));
                            if (icnt == 0)
                            {
                                sqlwh = string.Format(@"SELECT DISTINCT cWhCode,cWhName,  bWhpos  as bWhPos FROM AA_HoldAuth a
INNER JOIN warehouse w ON a.caccode= w.cwhcode
LEFT JOIN UFSystem..UA_Role b ON  a.cUserId=b.cGroup_Id  
WHERE cFuncId LIKE '%W%' AND CBusObId='warehouse' AND cwhmemo like '%PDA%'
AND( (isUserGroup =0 AND cUserId = '{0}')    OR (isUserGroup =1 AND b.cUser_Id = '{0}' ))", cuserid);

                            }
                        }

                    }
                    List<Warehouse> u8wms001s1 = db.Ado.SqlQuery<Warehouse>(sqlwh).ToList();

                    if (u8wms001s1.Count > 0)
                    {
                        
                        return DBService.ReOKObject(u8wms001s1);
                    }
                    else
                    {
                        return DBService.ReErrObject("查询不到仓库");
                    }
                }
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }

        }

        /// <summary>
        /// 读取仓库信息，根据编码或者名称
        /// </summary>
        /// <param name="cwhcode">编码或者名称</param>
        /// <returns></returns>
        public RetModel2 GetEntityByWhCode(string cwhcode)
        {
            try
            {
                using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = conStr,
                    DbType = SqlSugar.DbType.SqlServer,
                    IsAutoCloseConnection = true
                }))
                {

                    Warehouse pos = db.Queryable<Warehouse>().Where(x =>   (x.cWhCode == cwhcode || x.cWhName == cwhcode)).First();
                    if (pos != null)
                    {
                        
                       List<Warehouse> lst = new List<Warehouse> { pos };
                       return DBService.ReOKObject(lst);
                       
                    }
                    else
                    {
                        return DBService.ReErrObject("查询不到仓库！");
                    }
                }
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }
        
        }


        /// <summary>
        /// 导入U8，新增或修改
        /// </summary>
        /// <returns></returns>
        public RetModel2 Import()
        {

            try
            {
                //设置默认只
                this.entity.cWhValueStyle = "全月平均法";
                this.entity.bMRP = true;
                this.entity.iWHProperty = 0;
                this.entity.bShop = false;
                this.entity.bControlSerial = false;
                this.entity.bInCost = true;
                this.entity.bInAvailCalcu = true;
                this.entity.bProxyWh = false; 
                //检查是否存在这个编码
                bool binv = Exists(entity.cWhCode);

                if (!binv)
                {
                    
                    return this.Add();
                }
                else
                {
                    return this.Update();
                }

            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }



        }
        public RetModel2 Add()
        {
            try
            {
                string cerr;
                string cid;

                //末级编码系统自动处理了
                if (WarehouseDALCO.AddWarehouse(this.entity, xmlConfig, out cerr, out cid))
                {

                    return DBService.ReOKObject("新增完成");
                }
                else
                {
                    return DBService.ReErrObject(cerr);
                }

            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }
        }

        /// <summary>
        ///  变更
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public RetModel2 Update()
        {
            try
            {
                string cerr;
                string cid;
                if (WarehouseDALCO.ModifyWarehouse(this.entity, xmlConfig, out cerr))
                {

                    return DBService.ReOKObject("修改完成");
                }
                else
                {
                    return DBService.ReErrObject(cerr);
                }

            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }

        }

        public RetModel2 Delete()
        {
            try
            {
                string cerr;
                string cid;

                if (WarehouseDALCO.DelWarehouse(entity.cWhCode, xmlConfig, out cerr))
                {
                    return DBService.ReOKObject("删除完成");
                }
                else
                {
                    return DBService.ReErrObject(cerr);
                }

            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }
        }
        /// <summary>
        /// 检查仓库是否存在，返回U8仓库
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Warehouse GetByCode()
        {
            if (entity.cWhCode == null)
            {
                return null;
            }

            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            }))
            {

                Warehouse Computation = db.Queryable<Warehouse>().Where(x => x.cWhCode == entity.cWhCode).First();
                return Computation;
            }

        }
        /// <summary>
        /// 检查计量单位是否存在
        /// </summary>
        /// <param name="cCode"></param>
        /// <returns></returns>
        public bool Exists(string cCode)
        {

            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = CanShu.conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            }))
            {


                var cus = db.Queryable<Warehouse>().Where(x => x.cWhCode == cCode).First();
                if (cus == null)
                {
                    return false;
                }
                else
                {
                    return true;
                }




            }
        }

         
        public void MergeEntity()
        {
            AS_Warehouse entity2 = new AS_Warehouse();
            //取默认值合并
            entity = ASService.MergeEntity<AS_Warehouse>(entity, entity2);
        }
    }
}
